package cn.maxhou.controller;

import cn.maxhou.entity.Storage;
import cn.maxhou.entity.Supplier;
import cn.maxhou.entity.SysRole;
import cn.maxhou.entity.SysUser;
import cn.maxhou.service.StorageService;
import cn.maxhou.service.SupplierService;
import cn.maxhou.service.UploadService;
import cn.maxhou.util.Constants;
import cn.maxhou.util.Page;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/storageRecord")
public class Storageontroller extends BaseController{

    private static final Logger LOGGER= LoggerFactory.getLogger(Storageontroller.class);

    @Autowired
    private StorageService storageService;
    @Autowired
    private SupplierService supplierService;

    @ResponseBody
    @GetMapping("/srCodeExist")
    public String accountExist(@RequestParam String srCode) throws Exception {
        LOGGER.debug("检查入库单编号supCode={}的用户是否存在", srCode);
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        if (StringUtils.isEmpty(srCode)) {
            resultMap.put("exist", 0);
        } else {
            try {
                Storage storage = storageService.getBysrCode(srCode);
                if (storage != null) {
                    //已经存在,设置1
                    resultMap.put("exist", 1);
                } else {
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                LOGGER.error("Storageontroller中的accountExist方法执行发生错误", e);
                resultMap.put("error", "出现异常,请联系管理员处理!");
            }
        }
        System.out.println(JSON.toJSONString(resultMap));
        return JSON.toJSONString(resultMap);
    }
        @RequestMapping("/page")
    public String page(Model model, Storage condition,
                       @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize){
        Page<Storage> page=null;
        List<Supplier> supplierList=null;
        try{
            //查询用户的分页信息
            page=storageService.findPage(condition,pageNo,pageSize);
            supplierList = supplierService.getSupplierList();
            //将分页数据,角色列表和查询条件设置到模型数据中
            model.addAttribute("condition",condition);
            model.addAttribute("pageInfo",page);
            model.addAttribute("supplierList",supplierList);
        } catch (Exception e) {
            LOGGER.error("Storageontroller中的page方法执行发生的错误",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/page";
    }

    @GetMapping("/del/{id}")
    @ResponseBody
    public Map del(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
        HashMap resultMap=new HashMap<String,Object>();
        int flag=0;
        try{
            flag =storageService.deleteById(id);

            if (flag>0){
                resultMap.put("code",200);
                System.out.println("删除成功");
            }else {
                resultMap.put("code",500);
                resultMap.put("msg","删除失败");
            }

        } catch (Exception e) {
            LOGGER.error("Storageontroller中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return resultMap;
    }

    /**跳转到save.jsp页面的接口*/
    @GetMapping("/save")
    public String toSave(Model model){
        List<Supplier> supplierList=null;
        try{
            supplierList = supplierService.getSupplierList();
            //有角色下拉框需要数据
            model.addAttribute("supplierList",supplierList);
            //回显数据时需要sysUser,这里给个空对象避免出错
            model.addAttribute("storageRecord",new Storage());
        } catch (Exception e) {
            LOGGER.error("Storageontroller的toSave方法执行发生错误.",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }
    /**保存或修改数据接口*/
    @PostMapping("/save")
    public String doSave(Storage storage){
        try{
            //通过父类的session方法获取登录用户,由于泛型自动转换无需强转
            SysUser loginUser=session(Constants.SESSION_USER);
            if (storage.getId()==null){
                //如果是添加用户,关联传家用户为当前登录用户
                storage.setCreatedUserId(loginUser.getId());
                storage.setCreatedTime(new Date());
            }else {
                //如果是修改用户,管理修改用户为当前登录用户
                storage.setUpdatedUserId(loginUser.getId());
                storage.setUpdatedTime(new Date());
            }
            //新增和修改公用一个业务方法
            boolean ok=storageService.saveOrUpdate(storage);
            if (ok){
                //保存成功,跳回列表页面
                return redirect("/main/storageRecord/page");
            }
        } catch (Exception e) {
            LOGGER.error("Storageontroller中的doSave方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id")Long id,Model model){
        Storage storage=null;
        List<Supplier> supplierList=null;
        try{
            storage =storageService.findById(id);
            supplierList = supplierService.getSupplierList();
            //有角色下拉框需要数据
            model.addAttribute("supplierList",supplierList);
            //回显数据时需要sysUser,这里给个空对象避免出错
            model.addAttribute("storageRecord",storage);
        } catch (Exception e) {
            LOGGER.error("Storageontroller中的toEdit方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id,Model model) throws IOException{
        Storage storage=null;
        try{
            storage =storageService.findById(id);
            model.addAttribute("storageRecord",storage);
        } catch (Exception e) {
            LOGGER.error("Storageontroller中的view方法执行发生错误",e);
            throw new RuntimeException(e);
        }
        return "storageRecord/view";
    }

}
